package com.ruoyi.system.service.impl;

import java.util.*;
import java.util.stream.Collectors;
import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.dto.HospitalSubscribeGroupPurchaseOrderDto;
import com.ruoyi.system.domain.vo.HospitalSubscribeGroupPurchaseOrderVo;
import com.ruoyi.system.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.HospitalSubscribeGroupPurchaseOrderMapper;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

/**
 * 团队订单Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-06-12
 */
@Service
public class HospitalSubscribeGroupPurchaseOrderServiceImpl implements IHospitalSubscribeGroupPurchaseOrderService 
{
    @Autowired
    private HospitalSubscribeGroupPurchaseOrderMapper hospitalSubscribeGroupPurchaseOrderMapper;

    @Autowired
    private IHospitalSubscribeGroupPurchaseMedicalExaminerInfoService iHospitalSubscribeGroupPurchaseMedicalExaminerInfoService;

    @Autowired
    private IHospitalSubscribeGroupPurchaseInspectionResultsService iHospitalSubscribeGroupPurchaseInspectionResultsService;

    @Autowired
    private IHospitalSubscribeSetMealService iHospitalSubscribeSetMealService;

    @Autowired
    private IHospitalSubscribeProjectService iHospitalSubscribeProjectService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private IHospitalSubscribeOrderService iHospitalSubscribeOrderService;


    /**
     * 查询团队订单
     * 
     * @param id 团队订单主键
     * @return 团队订单
     */
    @Override
    public HospitalSubscribeGroupPurchaseOrder selectHospitalSubscribeGroupPurchaseOrderById(Long id)
    {
        return hospitalSubscribeGroupPurchaseOrderMapper.selectHospitalSubscribeGroupPurchaseOrderById(id);
    }

    /**
     * 查询团队订单列表
     * 
     * @param hospitalSubscribeGroupPurchaseOrder 团队订单
     * @return 团队订单
     */
    @Override
    public List<HospitalSubscribeGroupPurchaseOrder> selectHospitalSubscribeGroupPurchaseOrderList(HospitalSubscribeGroupPurchaseOrder hospitalSubscribeGroupPurchaseOrder)
    {
        return hospitalSubscribeGroupPurchaseOrderMapper.selectHospitalSubscribeGroupPurchaseOrderList(hospitalSubscribeGroupPurchaseOrder);
    }

    /**
     * 新增团队订单
     * 
     * @param hospitalSubscribeGroupPurchaseOrder 团队订单
     * @return 结果
     */
    @Override
    public int insertHospitalSubscribeGroupPurchaseOrder(HospitalSubscribeGroupPurchaseOrder hospitalSubscribeGroupPurchaseOrder)
    {
        hospitalSubscribeGroupPurchaseOrder.setCreateTime(DateUtils.getNowDate());
        return hospitalSubscribeGroupPurchaseOrderMapper.insertHospitalSubscribeGroupPurchaseOrder(hospitalSubscribeGroupPurchaseOrder);
    }

    /**
     * 修改团队订单
     * 
     * @param hospitalSubscribeGroupPurchaseOrder 团队订单
     * @return 结果
     */
    @Override
    public int updateHospitalSubscribeGroupPurchaseOrder(HospitalSubscribeGroupPurchaseOrder hospitalSubscribeGroupPurchaseOrder)
    {
        hospitalSubscribeGroupPurchaseOrder.setUpdateTime(DateUtils.getNowDate());
        return hospitalSubscribeGroupPurchaseOrderMapper.updateHospitalSubscribeGroupPurchaseOrder(hospitalSubscribeGroupPurchaseOrder);
    }

    /**
     * 批量删除团队订单
     * 
     * @param ids 需要删除的团队订单主键
     * @return 结果
     */
    @Override
    public int deleteHospitalSubscribeGroupPurchaseOrderByIds(Long[] ids)
    {
        return hospitalSubscribeGroupPurchaseOrderMapper.deleteHospitalSubscribeGroupPurchaseOrderByIds(ids);
    }

    /**
     * 删除团队订单信息
     * 
     * @param id 团队订单主键
     * @return 结果
     */
    @Override
    public int deleteHospitalSubscribeGroupPurchaseOrderById(Long id)
    {
        return hospitalSubscribeGroupPurchaseOrderMapper.deleteHospitalSubscribeGroupPurchaseOrderById(id);
    }

    /**
     * 新增团队订单
     *
     * @param dto
     * @return
     */
    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public boolean saveGroupPurchaseOrder(HospitalSubscribeGroupPurchaseOrderDto dto) {
        HospitalSubscribeGroupPurchaseOrderVo vo = new HospitalSubscribeGroupPurchaseOrderVo();

        // 订单主信息
        HospitalSubscribeGroupPurchaseOrder order = new HospitalSubscribeGroupPurchaseOrder();
        BeanUtils.copyProperties(dto, order);
        order.setOrderNo(UUID.randomUUID().toString().replace("-", ""));
        this.insertHospitalSubscribeGroupPurchaseOrder(order);

        BeanUtils.copyProperties(order,vo);

        // 套餐信息
        Long setMealId = dto.getSetMealId();
        HospitalSubscribeSetMeal hospitalSubscribeSetMeal = iHospitalSubscribeSetMealService.selectHospitalSubscribeSetMealById(setMealId);
        if (hospitalSubscribeSetMeal == null || hospitalSubscribeSetMeal.getIsShow() == 1) {
            throw new RuntimeException("该套餐不存在或已下架");
        }

        // 对应检查项目
        List<String> projectIds = Arrays.stream(hospitalSubscribeSetMeal.getProjectIds().split(",")).collect(Collectors.toList());
        List<HospitalSubscribeProject> subscribeProject = iHospitalSubscribeProjectService.getHospitalSubscribeProjectByIds(projectIds);

        // 体检人信息
        List<HospitalSubscribeGroupPurchaseMedicalExaminerInfo> examinerInfoList = dto.getExaminerInfoList();
        if (CollectionUtils.isEmpty(examinerInfoList)) {
            throw new RuntimeException("请添加团队体检人信息");
        }


        for (HospitalSubscribeGroupPurchaseMedicalExaminerInfo examinerInfo : examinerInfoList) {
            iHospitalSubscribeGroupPurchaseMedicalExaminerInfoService.insertHospitalSubscribeGroupPurchaseMedicalExaminerInfo(examinerInfo);
            List<HospitalSubscribeGroupPurchaseInspectionResults> resultsList = new ArrayList<>();
            for (HospitalSubscribeProject project : subscribeProject) {
                // 体检人结果
                HospitalSubscribeGroupPurchaseInspectionResults results = new HospitalSubscribeGroupPurchaseInspectionResults();
                results.setOrderNo(order.getOrderNo());
                results.setPhone(examinerInfo.getPhone());
                results.setItemId(project.getId());
                results.setItemName(project.getProjectName());

                resultsList.add(results);
            }
            examinerInfo.setResultsList(resultsList);
        }
        vo.setExaminerInfoList(examinerInfoList);
        stringRedisTemplate.opsForValue().set("GROUP_PURCHASE_ORDER_"+order.getId(), JSON.toJSONString(vo));
        return true;
    }

    /**
     * 团队订单详情
     * @param hospitalSubscribeGroupPurchaseOrder
     * @return
     */
    @Override
    public HospitalSubscribeGroupPurchaseOrderVo getGroupPurchaseOrderInfo(HospitalSubscribeGroupPurchaseOrder hospitalSubscribeGroupPurchaseOrder) {
        return hospitalSubscribeGroupPurchaseOrderMapper.getGroupPurchaseOrderInfo(hospitalSubscribeGroupPurchaseOrder);
    }

    /**
     * 保存团队订单详情 缓存
     * @param vo
     * @return
     */
    @Override
    public boolean saveGroupPurchaseOrderInfo(HospitalSubscribeGroupPurchaseOrderVo vo) {
        stringRedisTemplate.opsForValue().set("GROUP_PURCHASE_ORDER_"+vo.getId(), JSON.toJSONString(vo));
        return true;
    }

    /**
     * 查看团队订单详情 缓存
     * @param id
     * @return
     */
    @Override
    public HospitalSubscribeGroupPurchaseOrderVo getGroupPurchaseOrderInfoCache(Long id) {
        return JSON.parseObject(stringRedisTemplate.opsForValue().get("GROUP_PURCHASE_ORDER_"+id),HospitalSubscribeGroupPurchaseOrderVo.class);
    }

    /**
     * 提交团队订单
     * @param vo
     * @return
     */
    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public boolean submitGroupPurchaseOrderInfo(HospitalSubscribeGroupPurchaseOrderVo vo) {
        // 订单信息
        HospitalSubscribeGroupPurchaseOrderVo orderVo = this.getGroupPurchaseOrderInfoCache(vo.getId());
        String codeUrl = iHospitalSubscribeOrderService.getCodeUrl("www.whjxzfjwsfwzx.cn/prod-api/applet/group/purchase/order/getGroupPurchaseOrderInfo?orderNo=" + vo.getOrderNo());
        HospitalSubscribeGroupPurchaseOrder order = new HospitalSubscribeGroupPurchaseOrder();
        order.setId(orderVo.getId());
        order.setStatus(1);
        order.setCodeUrl(codeUrl);
        this.updateHospitalSubscribeGroupPurchaseOrder(order);


        Map<String, String> map = orderVo.getExaminerInfoList().stream().peek(item -> {
            item.setCodeUrl(iHospitalSubscribeOrderService.getCodeUrl("www.whjxzfjwsfwzx.cn/prod-api/applet/group/purchase/inspection/results/getResultsByOrderNoAndPhone?orderNo=" + vo.getOrderNo()));
        }).collect(Collectors.toMap(HospitalSubscribeGroupPurchaseMedicalExaminerInfo::getPhone, HospitalSubscribeGroupPurchaseMedicalExaminerInfo::getCodeUrl));

        // 检查结果
        for (HospitalSubscribeGroupPurchaseMedicalExaminerInfo info : orderVo.getExaminerInfoList()) {
            for (HospitalSubscribeGroupPurchaseInspectionResults results : info.getResultsList()) {
                results.setCodeUrl(map.get(results.getPhone()));
                iHospitalSubscribeGroupPurchaseInspectionResultsService.insertHospitalSubscribeGroupPurchaseInspectionResults(results);
            }
        }

        // 删除缓存信息
        stringRedisTemplate.delete("GROUP_PURCHASE_ORDER_"+vo.getId());
        return true;
    }


}
